﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using Tesla.Graphics;
using Tesla.Graphics.Implementation;
using D3D = SlimDX.Direct3D10;

namespace Tesla.Direct3D10.Graphics.Implementation {
    /// <summary>
    /// Concrete Direct3D10 implementation for <see cref="DepthStencilState"/>.
    /// </summary>
    public sealed class D3D10DepthStencilStateImplementation : DepthStencilStateImplementation {
        private D3D10Renderer _renderer;
        private D3D.Device _graphicsDevice;
        private D3D.DepthStencilState _ds;

        /// <summary>
        /// Gets the D3D10Renderer that created this implementation.
        /// </summary>
        internal D3D10Renderer Renderer {
            get {
                return _renderer;
            }
        }

        /// <summary>
        /// Gets the D3D10 DepthStencilState.
        /// </summary>
        internal D3D.DepthStencilState D3D10DepthStencilState {
            get {
                return _ds;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="D3D10DepthStencilStateImplementation"/>.
        /// </summary>
        /// <param name="renderer">The D3D10 renderer.</param>
        internal D3D10DepthStencilStateImplementation(D3D10Renderer renderer) 
            : base() {
                _renderer = renderer;
                _graphicsDevice = renderer.GraphicsDevice;
        }

        /// <summary>
        /// Binds the implementation. This is called the first time an unbound state is set to the device or manually by the user in order to
        /// create the underlying state ahead of time (best practice). Once called the state properties are read-only.
        /// </summary>
        public override void BindDepthStencilState() {
            if(!base.IsBound) {
                D3D.DepthStencilStateDescription desc = new D3D.DepthStencilStateDescription();

                desc.DepthWriteMask = (base.DepthWriteEnable) ? D3D.DepthWriteMask.All : D3D.DepthWriteMask.Zero;
                desc.DepthComparison = D3D10Helper.ToD3DComparison(base.DepthFunction);
                desc.IsDepthEnabled = base.DepthEnable;
                desc.IsStencilEnabled = base.StencilEnable;
                desc.StencilWriteMask = (byte) base.StencilWriteMask;
                desc.StencilReadMask = (byte) base.StencilReadMask;

                //Set front facing stencil op
                D3D.DepthStencilOperationDescription opDesc = new D3D.DepthStencilOperationDescription();
                opDesc.Comparison = D3D10Helper.ToD3DComparison(base.StencilFunction);
                opDesc.DepthFailOperation = D3D10Helper.ToD3DStencilOperation(base.StencilDepthFail);
                opDesc.FailOperation = D3D10Helper.ToD3DStencilOperation(base.StencilFail);
                opDesc.PassOperation = D3D10Helper.ToD3DStencilOperation(base.StencilPass);
                desc.FrontFace = opDesc;

                D3D.DepthStencilOperationDescription ccwopDesc = new D3D.DepthStencilOperationDescription();
                //Set back facing stencil op if enabled, otherwise enforced defaults
                if(base.TwoSidedStencilEnable) {
                    ccwopDesc.Comparison = D3D10Helper.ToD3DComparison(base.CounterClockwiseStencilFunction);
                    ccwopDesc.DepthFailOperation = D3D10Helper.ToD3DStencilOperation(base.CounterClockwiseStencilDepthFail);
                    ccwopDesc.FailOperation = D3D10Helper.ToD3DStencilOperation(base.CounterClockwiseStencilFail);
                    ccwopDesc.PassOperation = D3D10Helper.ToD3DStencilOperation(base.CounterClockwiseStencilPass);
                } else {
                    ccwopDesc.Comparison = D3D.Comparison.Always;
                    ccwopDesc.DepthFailOperation = D3D.StencilOperation.Keep;
                    ccwopDesc.FailOperation = D3D.StencilOperation.Keep;
                    ccwopDesc.PassOperation = D3D.StencilOperation.Keep;
                }
                desc.BackFace = ccwopDesc;
                
                _ds = D3D.DepthStencilState.FromDescription(_graphicsDevice, desc);
                base.IsBound = true;

                _renderer.Resources.AddTrackedObject(_ds.ComPointer, this);
            }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="D3D10DepthStencilStateImplementation"/> is reclaimed by garbage collection.
        /// </summary>
        ~D3D10DepthStencilStateImplementation() {
            Dispose(false);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing) {
            if(!IsDisposed) {
                //Dispose of managed resources
                if(disposing) {
                    if(_ds != null) {
                        if(_renderer != null) {
                            _renderer.Resources.RemoveTrackedObject(_ds.ComPointer);
                        }
                        _ds.Dispose();
                        _ds = null;
                    }
                }
                base.Dispose(disposing);
            }
        }
    }
}
